package br.usp.ime.dojo.server;

import br.usp.ime.dojo.client.DojoException;
import br.usp.ime.dojo.client.IdentificationService;
import br.usp.ime.dojo.client.SessionDTO;
import br.usp.ime.dojo.client.UserDTO;
import br.usp.ime.dojo.core.entities.User;
import br.usp.ime.dojo.core.exceptions.DuplicatedUserException;
import br.usp.ime.dojo.core.repositories.RepositoryFactory;
import br.usp.ime.dojo.core.repositories.SessionRepository;
import br.usp.ime.dojo.core.repositories.UserRepository;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class IdentificationServiceImpl extends RemoteServiceServlet implements IdentificationService {

	private static final long serialVersionUID = 1L;
	
	public UserDTO identify(String name) throws DojoException {
		try {
			UserRepository userRepository = RepositoryFactory.createUserRepository();
			User user = new User(name);
			userRepository.add(user);
			return Convert.fromUser(user);
		} catch (DuplicatedUserException e) {
			throw new DojoException(e.getMessage());
		}
		
	}

	public UserDTO getUser(String name) {
		UserRepository userRepository = RepositoryFactory.createUserRepository();
		return Convert.fromUser(userRepository.get(name));
	}
	
	public SessionDTO getSession(String sessionId){
		SessionRepository sessionRepository = RepositoryFactory.createSessionRepository();
		return Convert.fromSession(sessionRepository.get(sessionId));
	}
	
	public void addSession(SessionDTO session) {
		SessionRepository sessionRepository = RepositoryFactory.createSessionRepository();
		sessionRepository.add(Convert.toSession(session));
	}
}
